import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { MatDialog, MatMenuTrigger } from '@angular/material';
import { DataService } from '../services/data.service';
import { LoginService } from './../services/login.service';
import { ElasticsearchService } from './../services/elasticsearch.service';
import { RestService } from '../services/rest.service';

import * as _ from 'lodash';

@Component({
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit, OnDestroy {
  lastRecordRoutine: any;

  constructor(private router: Router,
              private dataService: DataService,
              private restService: RestService,
              private loginService: LoginService,
              private elastic: ElasticsearchService) {
  }

  navigateTo(item) {
    this.router.navigateByUrl('/home/' + item);
  }

  logout(event) {
    this.loginService.logOut();
  }

  ngOnInit() {
    this.elastic.getLatestRecord(data => {
      if (_.isEmpty(data.data)) {
        // no data were trieved
        this.startRoutine();
        return;
      }

      this.elastic.lastRecord = data.data;
      this.dataService.updateData(data.data);
      this.startRoutine();
    });
  }

  startRoutine() {
    if (this.lastRecordRoutine) {
      clearInterval(this.lastRecordRoutine);
    }

    this.lastRecordRoutine = setInterval(() => {
      this.elastic.getLatestRecord(data => {
        if (_.isEmpty(data.data)) {
          // no data were trieved
          return;
        }

        this.elastic.lastRecord = data.data;
        this.dataService.updateData(data.data);
      });
    }, this.elastic.INTERVAL * 1000);
  }

  ngOnDestroy() {
    if (this.lastRecordRoutine) {
      clearInterval(this.lastRecordRoutine);
    }
  }
}
